# coding=utf8

from pyjvm.instructions.common import ClassInitializer
from pyjvm.runtime.metadata import Method
from pyjvm.runtime.strpool import StringPool
from pyjvm.runtime.thread import Frame


def hacked_invoke_static(method: Method, frame: Frame):
    if method.klass.name == 'java/lang/System' and method.name == 'loadLibrary':
        frame.operand_stack.pop()
        return True

    if method.klass.name == 'java/lang/Class' and method.name == 'forName' \
            and len(method.parameter_types) == 3:
        # caller = frame.operand_stack[-1]
        initialize = frame.operand_stack[-2]
        j_name = frame.operand_stack[-3]

        py_name = StringPool.to_py_str(j_name).replace('.', '/')
        klass = frame.method.klass.loader.load_class(py_name)
        j_class = klass.j_class

        if initialize and not klass.inited:
            thread = frame.thread
            frame.set_next_pc(thread.pc)
            ClassInitializer.init_class(thread, klass)
        else:
            frame.operand_stack.pop()
            frame.operand_stack.pop()
            frame.operand_stack.pop()
            frame.operand_stack.push(j_class)
        return True


__all__ = ['hacked_invoke_static']
